import requests
import logging
from config.config import AMAP_KEY, CITY_ADCODE

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class WeatherService:
    def __init__(self):
        self.base_url = "https://restapi.amap.com/v3/weather/weatherInfo"
        
    def get_weather(self):
        """获取高德地图天气数据"""
        params = {
            'key': AMAP_KEY,
            'city': CITY_ADCODE,
            'extensions': 'base',
            'output': 'JSON'
        }
        
        try:
            logger.info("正在获取天气数据...")
            response = requests.get(self.base_url, params=params)
            response.raise_for_status()
            data = response.json()
            
            if data['status'] == '1':
                weather = data['lives'][0]
                logger.info(f"成功获取天气数据: 温度={weather['temperature']}°C, 湿度={weather['humidity']}%")
                return {
                    'province': weather['province'],
                    'city': weather['city'],
                    'temperature': float(weather['temperature_float']),  # 使用更精确的浮点数温度
                    'humidity': float(weather['humidity_float']),      # 使用更精确的浮点数湿度
                    'weather': weather['weather'],
                    'winddirection': weather['winddirection'],
                    'windpower': weather['windpower'],
                    'reporttime': weather['reporttime']
                }
            else:
                logger.error(f"获取天气数据失败: {data['info']}")
                return None
                
        except Exception as e:
            logger.error(f"获取天气数据出错: {str(e)}")
            return None